<?php
declare (strict_types = 1);

namespace app\index\controller;

use app\index\BaseController;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Log;
use app\index\model\Comment as CommentModel;
use app\common\validate\Comment as CommentValidate;

class Comment extends BaseController
{
    //中间件
    protected $middleware = [
        'method:ajax' => ['only'=>['comment','list','delete']],
        'access:@' => ['only'=>['comment','delete']],
    ];


    /**
     * 前台提交评论
     */
    public function comment(){
        try{
            //验证数据
            $data = request()->only(['comment','article_id','parent_id']);
            validate(CommentValidate::class)->check($data);

            $ret=$this->getModel(CommentModel::class)
                ->checkLimit() //限制速率
                ->save($data);

            if( !$ret )
                throw new Exception('评论失败,请重试.');
            return json([
                'code' => 0,
                'msg' => '评论成功.'
            ]);
        } catch (ValidateException $e) {
            //验证错误
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        } catch (\Exception $e){
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 前台删除评论
     */
    public function delete(int $comment_id){
        try{
            //获取参数
            $model = $this->getModel(CommentModel::class,
                $comment_id,
                ['replies']);
            if ((int)$model->article_id != input('article_id/d'))
                throw new Exception('参数错误.');
            if ((int)$model->user_id !== (int)app()->user->getId())
                throw new Exception('您无权操作.');

            if (!$model->together(['replies'])->delete())
                throw new Exception('删除失败.');

            return json([
                'code' => 0,
                'msg' => '删除成功.'
            ]);
        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取评论列表
     */
    public function list(){
        try{
            //获取标签ID
            $article_id = input('article_id/d');
            if ($article_id <= 0) throw new Exception('参数错误.');


            //获取参数
            $page = input('page/d');
            $limit= input('limit/d');
            $data = CommentModel::getList($page, $limit, $article_id);

            return json([
                'code' => 0,
                'data'  => $data
            ]);
        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg'  => $e->getMessage()
            ]);
        }
    }

}
